/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlink.component.resolver.impl;

import com.xuexiang.xdlink.component.command.IHandleMessageCommand;
import com.xuexiang.xdlink.component.message.IResponseMessage;
import com.xuexiang.xdlink.component.resolver.IMessageResolver;
import com.xuexiang.xdlink.exception.ProtocolException;
import com.xuexiang.xdlink.exception.ResolverException;

import java.util.ArrayList;
import java.util.List;

/**
 * 抽象的消息解析器
 *
 * @author xuexiang
 * @since 2018/8/13 下午10:45
 */
public abstract class AbstractMessageResolver implements IMessageResolver {

    /**
     * 用于缓存解析出的消息（每次解析前都需要清除）
     */
    private List<IResponseMessage> mMessages = new ArrayList<>();

    /**
     * 拆分、解析接收到的原始数据
     *
     * @param data 接收到的原始数据
     * @return 返回已解析数据的长度
     * @throws ResolverException
     */
    @Override
    public int resolve(byte[] data) throws ResolverException {
        clearMessages(); //每次解析前都需要清一下缓存
        return resolveData(data);  //做具体的解析工作
    }

    /**
     * 拆分、解析接收到的原始数据
     *
     * @param data 接收到的原始数据
     * @return 返回已解析数据的长度
     * @throws ResolverException
     */
    protected abstract int resolveData(byte[] data) throws ResolverException;

    @Override
    public void handleMessage(IHandleMessageCommand command) throws ProtocolException {
        if (command != null && hasMessages()) {
            command.handleMessage(mMessages);
        }
    }

    @Override
    public void recycle() {
        clearMessages();
    }

    /**
     * 加入消息
     *
     * @param message
     */
    protected void putMessage(IResponseMessage message) {
        if (mMessages != null && message != null) {
            mMessages.add(message);
        }
    }

    /**
     * 加入消息
     *
     * @param messages
     */
    protected void putMessages(List<IResponseMessage> messages) {
        if (mMessages != null && messages != null && !messages.isEmpty()) {
            mMessages.addAll(messages);
        }
    }

    /**
     * 清除消息
     */
    private void clearMessages() {
        if (hasMessages()) {
            mMessages.clear();
        }
    }

    /**
     * 是否存在已解析的消息
     */
    private boolean hasMessages() {
        return mMessages != null && !mMessages.isEmpty();
    }
}
